package lib

import (
	"honeyweb/broker"
	"honeyweb/log"
	"honeyweb/model"
)

func RPCClientRequest(method string, params, result interface{}) error {
	req, err := model.NewJsonReq(0, method, params, nil )
	if err != nil {
		log.S().Errorf("new json req err: %v", err)
		return err
	}
	if data, err := model.Encode(req); err != nil {
		log.S().Errorf("encode req err: %v", err)
		return err
	} else {
		subject := broker.GetSubjectByMethod(method)
		if subject == "" {
			log.S().Debugf("not found subject by method: %s",method)
			return err
		}
		rdata, err := broker.Request(subject,  data)
		if err != nil {
			log.S().Errorf("request err: %v", err)
			return err
		}
		resp, err := model.NewJsonRespByByte(rdata)
		if err != nil {
			log.S().Errorf("decode err: %v", err)
			return err
		}
		if resp.Error != nil {
			log.S().Errorf("resp err: %v", resp.Error)
			return resp.Error.(error)
		}
		model.DecodeFromString(resp.Result, result)
		log.S().Debugf("method:%s params:%+v result: %+v", method, params, result)
	}
	return nil
}

